<template>
  <transition name="fade">
    <!-- 筛选区 -->
    <div class="sub-filter" v-if="subCate.saleProperties">
      <div class="item" v-for="item in list" :key="item.id">
        <div class="head">{{ item.name }}：</div>
        <div class="body">
          <a
            href="javascript:;"
            :class="{ active: !item.activeText }"
            @click="handleFilter(item)"
            >全部</a
          >
          <a
            :class="{ active: item.activeText === item2.name }"
            href="javascript:;"
            v-for="item2 in item.properties"
            :key="item2.id"
            @click="handleFilter(item, item2.name)"
          >
            {{ item2.name }}
          </a>
        </div>
      </div>
    </div>
    <!-- 骨架屏 -->
    <div v-else class="sub-filter">
      <XtxSkeleton class="item" width="800px" height="40px" />
      <XtxSkeleton class="item" width="800px" height="40px" />
      <XtxSkeleton class="item" width="600px" height="40px" />
      <XtxSkeleton class="item" width="600px" height="40px" />
      <XtxSkeleton class="item" width="600px" height="40px" />
    </div>
  </transition>
</template>

<script>
import { computed, inject, reactive, toRef, watch } from 'vue'
export default {
  name: 'SubFilter',
  setup () {
    // 渲染数据
    const subCate = inject('subCate')

    const brand = reactive({
      id: null,
      name: '品牌',
      properties: computed(() => subCate.value.brands)
    })
    const list = computed(() => [brand, ...subCate.value.saleProperties])

    // 筛选过滤
    const sortParams = inject('sortParams')
    const handleFilter = (theItem, propertyName) => {
      const groupName = theItem.name
      const attrs = toRef(sortParams, 'attrs')
      const index = attrs.value.findIndex(item => item.groupName === groupName)
      // 高亮样式
      theItem.activeText = propertyName
      // 点击全部 - 删除对应对象
      if (!propertyName) return attrs.value.splice(index, 1)
      // 品牌不存在 - push 新对象
      if (index === -1) attrs.value.push({ groupName, propertyName })
      // 品牌已存在 - 覆盖 propertyName
      if (index !== -1) attrs.value[index].propertyName = propertyName
    }

    watch(
      () => subCate.value.saleProperties,
      () => (brand.activeText = null),
      { deep: true }
    )

    return { list, subCate, handleFilter, sortParams }
  }
}
</script>

<style scoped lang="less">
.xtx-skeleton {
  padding: 10px 0;
}
// 筛选区
.sub-filter {
  background: #fff;
  padding: 25px;
  .item {
    display: flex;
    line-height: 40px;
    .head {
      width: 80px;
      color: #999;
    }
    .body {
      flex: 1;
      a {
        margin-right: 36px;
        transition: all 0.3s;
        display: inline-block;
        &.active,
        &:hover {
          color: @xtxColor;
        }
      }
    }
  }
}
</style>
